import { LLMAdapter, ModelInfo, ValidationResult, ValidationErrorCode } from '../../types/index';

export class OpenRouterAdapter implements LLMAdapter {
  private readonly timeout = 10000; // 10秒超时

  async fetchModels(baseURL = 'https://openrouter.ai/api/v1', apiKey?: string): Promise<ModelInfo[]> {
    try {
      const modelsUrl = `${baseURL}/models`;
      const headers: HeadersInit = {
        'Content-Type': 'application/json',
      };
      
      // 如果提供了apiKey，添加认证头
      if (apiKey) {
        headers['Authorization'] = `Bearer ${apiKey}`;
      }
      
      const response = await this.makeRequest(modelsUrl, {
        method: 'GET',
        headers,
      });

      if (response.ok) {
        const data = await response.json();
        return this.parseModels(data.data || []);
      } else {
        // 如果API调用失败，返回静态模型列表
        return this.getStaticModels();
      }
    } catch (error) {
      console.warn('Failed to fetch OpenRouter models from', baseURL, ':', error);
      return this.getStaticModels();
    }
  }

  async validateApiKey(apiKey: string, baseURL = 'https://openrouter.ai/api/v1'): Promise<ValidationResult> {
    if (!apiKey || !apiKey.trim()) {
      return {
        isValid: false,
        error: {
          code: ValidationErrorCode.INVALID_API_KEY,
          message: 'API Key 不能为空',
          suggestion: '请输入有效的 OpenRouter API Key'
        }
      };
    }

    try {
      // 首先尝试获取账户信息
      const accountResponse = await this.makeRequest(`${baseURL}/auth/key`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json',
        },
      });

      if (accountResponse.ok) {
        const accountData = await accountResponse.json();
        return {
          isValid: true,
          metadata: {
            accountInfo: accountData.data,
            availableModels: accountData.data?.models || []
          }
        };
      } else {
        const errorData = await accountResponse.json().catch(() => ({}));
        return this.handleErrorResponse(accountResponse.status, errorData);
      }
    } catch (error) {
      return this.handleNetworkError(error);
    }
  }

  private async makeRequest(url: string, options: RequestInit): Promise<Response> {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);

    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal,
      });
      clearTimeout(timeoutId);
      return response;
    } catch (error) {
      clearTimeout(timeoutId);
      throw error;
    }
  }

  private parseModels(models: any[]): ModelInfo[] {
    return models
      .filter(model => model.id && typeof model.id === 'string')
      .map(model => ({
        id: model.id,
        name: model.name || model.id,
        provider: 'openrouter',
        description: model.description || `OpenRouter model: ${model.id}`,
        contextLength: model.context_length || 4096,
        capabilities: this.parseCapabilities(model),
        pricing: model.pricing ? {
          input: parseFloat(model.pricing.prompt) || 0,
          output: parseFloat(model.pricing.completion) || 0,
        } : undefined,
      }))
      .sort((a, b) => a.name.localeCompare(b.name));
  }

  private parseCapabilities(model: any): string[] {
    const capabilities = ['text'];
    
    if (model.architecture && model.architecture.modality?.includes('vision')) {
      capabilities.push('vision');
    }
    
    if (model.id.includes('gpt-4') || model.id.includes('claude') || model.id.includes('gemini')) {
      capabilities.push('advanced-reasoning');
    }

    if (model.id.includes('code') || model.name?.toLowerCase().includes('code')) {
      capabilities.push('coding');
    }

    return capabilities;
  }

  private getStaticModels(): ModelInfo[] {
    return [
      {
        id: 'openai/gpt-4o',
        name: 'GPT-4o',
        provider: 'openrouter',
        description: 'OpenAI GPT-4o via OpenRouter',
        contextLength: 128000,
        capabilities: ['text', 'vision', 'advanced-reasoning'],
      },
      {
        id: 'openai/gpt-4o-mini',
        name: 'GPT-4o mini',
        provider: 'openrouter',
        description: 'OpenAI GPT-4o mini via OpenRouter',
        contextLength: 128000,
        capabilities: ['text', 'vision'],
      },
      {
        id: 'anthropic/claude-3.5-sonnet',
        name: 'Claude 3.5 Sonnet',
        provider: 'openrouter',
        description: 'Anthropic Claude 3.5 Sonnet via OpenRouter',
        contextLength: 200000,
        capabilities: ['text', 'vision', 'advanced-reasoning', 'coding'],
      },
      {
        id: 'anthropic/claude-3-opus',
        name: 'Claude 3 Opus',
        provider: 'openrouter',
        description: 'Anthropic Claude 3 Opus via OpenRouter',
        contextLength: 200000,
        capabilities: ['text', 'vision', 'advanced-reasoning'],
      },
      {
        id: 'google/gemini-pro-1.5',
        name: 'Gemini Pro 1.5',
        provider: 'openrouter',
        description: 'Google Gemini Pro 1.5 via OpenRouter',
        contextLength: 1000000,
        capabilities: ['text', 'vision', 'advanced-reasoning'],
      },
      {
        id: 'meta-llama/llama-3.1-405b-instruct',
        name: 'Llama 3.1 405B Instruct',
        provider: 'openrouter',
        description: 'Meta Llama 3.1 405B Instruct via OpenRouter',
        contextLength: 131072,
        capabilities: ['text', 'advanced-reasoning', 'coding'],
      },
    ];
  }

  private handleErrorResponse(status: number, errorData: any): ValidationResult {
    switch (status) {
      case 401:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.INVALID_API_KEY,
            message: 'API Key 无效或已过期',
            suggestion: '请检查 API Key 是否正确，并确认账户状态正常'
          }
        };
      case 403:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.INSUFFICIENT_PERMISSIONS,
            message: '权限不足或账户被限制',
            suggestion: '请检查账户状态和 API 使用权限'
          }
        };
      case 429:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.RATE_LIMITED,
            message: '请求频率过高',
            suggestion: '请降低请求频率或升级账户计划'
          }
        };
      case 500:
      case 502:
      case 503:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.SERVER_ERROR,
            message: 'OpenRouter 服务器错误',
            suggestion: '请稍后重试'
          }
        };
      default:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.UNKNOWN_ERROR,
            message: errorData.error?.message || '未知错误',
            suggestion: '请检查配置并重试'
          }
        };
    }
  }

  private handleNetworkError(error: any): ValidationResult {
    if (error.name === 'AbortError') {
      return {
        isValid: false,
        error: {
          code: ValidationErrorCode.TIMEOUT,
          message: '请求超时',
          suggestion: '请检查网络连接或稍后重试'
        }
      };
    }

    return {
      isValid: false,
      error: {
        code: ValidationErrorCode.NETWORK_ERROR,
        message: '网络连接错误',
        suggestion: '请检查网络连接并重试'
      }
    };
  }
}